package net.mudfox.stage;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import net.mudfox.base.BaseRestActivity;
import net.mudfox.factory.Entry;
import net.mudfox.factory.ID;
import net.mudfox.factory.Url;
import net.mudfox.helper.AdapterHelper;
import net.mudfox.helper.CommonHelper;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseRestActivity {
    SwipeRefreshLayout swipeLayout;
    ListView listView;
    ArrayAdapter<String> adapter;
    boolean scanFlag;
    List<String> tickets;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        actionBar.setDisplayHomeAsUpEnabled(false);

        entry = Entry.Ticket;
        baseUrl = Url.Ticket;
        tickets = new ArrayList<>();
        adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1);
        listView = findViewById(R.id.listView);
        listView.setAdapter(adapter);

        swipeLayout = findViewById(R.id.swipeLayout);
        swipeLayout.setOnRefreshListener(() -> {
            swipeLayout.setRefreshing(false);
            updateView();
        });

        scanFlag = checkPermission();
        updateView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, ID.ACTION_SEARCH, 0, "搜索");
        menu.add(0, ID.ACTION_COUNT, 1, "计数");
        menu.add(0, ID.ACTION_ADD, 2, "手动输入");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case ID.ACTION_ADD:
                return onAction_Add();
            case ID.ACTION_SEARCH:
                return onAction_Search();
            case ID.ACTION_COUNT:
                String reply = "当前总数： " + String.valueOf(listView.getAdapter().getCount());
                CommonHelper.showMessageLong(this, reply);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    boolean onAction_Add() {
        final EditText editText = new EditText(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("单号输入").setView(editText);
        builder.setPositiveButton("确定",
                (paramAnonymousDialogInterface, paramAnonymousInt) ->
                {
                    String ticket = editText.getText().toString().trim();
                    if (!ticket.isEmpty())
                        addTicket(ticket);
                });

        builder.setNegativeButton("取消",
                (paramAnonymousDialogInterface, paramAnonymousInt) -> {
                });

        builder.create().show();
        return true;
    }

    boolean onAction_Search() {
        final EditText editText = new EditText(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("单号搜索").setView(editText);
        builder.setPositiveButton("确定",
                (paramAnonymousDialogInterface, paramAnonymousInt) ->
                {
                    String kw = editText.getText().toString().trim();
                    if (!kw.isEmpty())
                        httpGet(baseUrl + "search/" + kw);
                });

        builder.setNegativeButton("取消",
                (paramAnonymousDialogInterface, paramAnonymousInt) -> {
                });

        builder.create().show();
        return true;
    }

    boolean checkPermission() {
        int permission = ActivityCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA);

        return permission == PackageManager.PERMISSION_GRANTED;
    }

    void requestPermission() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CAMERA}, ID.CODE_SCANNER);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == ID.CODE_SCANNER) {
            int grantResult = grantResults[0];
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                scanFlag = false;
                CommonHelper.showMessage(this, "您拒绝了程序运行所需要的权限！");
            } else {
                scanFlag = true;
                startActivityForResult(new Intent(this,
                        CodeScannerActivity.class), ID.CODE_SCANNER);
            }
        }
    }

    void updateView() {
        httpGet(baseUrl + "detail");
    }

    public void onBtnScan_Click(View v) {
        if (scanFlag)
            startActivityForResult(new Intent(this,
                    CodeScannerActivity.class), ID.CODE_SCANNER);
        else
            requestPermission();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;

        if (resultCode == ID.RESULT_DONE && requestCode == ID.CODE_SCANNER) {
            String code = data.getStringExtra("code");
            if (code.isEmpty())
                return;

            addTicket(code);
        }
    }

    void addTicket(String ticket) {
        if (tickets.contains(ticket)) {
            CommonHelper.showMessage(this, ticket + " 已存在");
            return;
        }
        httpGet(baseUrl + "add/" + ticket);
    }

    @Override
    public void processReply(JSONObject rootObject) {
        if (!rootObject.containsKey("entry") ||
                !rootObject.getString("entry").equals(entry))
            return;

        if (rootObject.containsKey("item")) {
            JSONObject object = rootObject.getJSONObject("item");
            String ticket = object.getString("ticket");
            tickets.add(ticket);

            String item = object.getString("date_") + "  " +
                    object.getString("time_") + "  " +
                    ticket;
            adapter.add(item);
        } else {
            JSONArray array = AdapterHelper.verifyObject(rootObject, entry);
            if (array.isEmpty()) {
                listView.setAdapter(null);
                return;
            }

            if (!tickets.isEmpty())
                tickets.clear();

            List<String> items = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                JSONObject object = array.getJSONObject(i);
                String ticket = object.getString("ticket");
                tickets.add(ticket);

                String item = object.getString("date_") + "  " +
                        object.getString("time_") + "  " +
                        ticket;
                items.add(item);
            }
            adapter = AdapterHelper.getArrayAdapter(this, items);
            listView.setAdapter(adapter);
        }
    }
}
